package com.koron.css2.meterService.impl;

import com.koron.css2.ServerInterface;
import com.koron.css2.meterService.bean.MsChgPlanBean;
import com.koron.css2.meterService.bean.MsChgPlanDetailBean;
import com.koron.css2.meterService.mapper.MsChgPlanDetailMapper;
import com.koron.css2.meterService.mapper.MsChgPlanMapper;
import com.koron.css2.serviceManage.bean.RequestBean;
import com.koron.css2.serviceManage.bean.UserInfoBean;
import com.koron.css2.serviceManage.utils.JsonUtils;
import com.koron.util.Constant;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.bson.types.ObjectId;
import org.koron.ebs.mybatis.SessionFactory;
import org.swan.bean.MessageBean;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 换表修改
 * @author 周利斌
 *
 */
public class MsChgUpdate implements ServerInterface{
	
	private static Logger log = LogManager.getLogger(MsChgUpdate.class);
	
	@Override
	public MessageBean<?> exec(SessionFactory factory, UserInfoBean userInfo, RequestBean req) {
		MessageBean<Map> info = MessageBean.create(Constant.MESSAGE_INT_SUCCESS, "修改成功", Map.class);
		try {
			MsChgPlanBean msChgPlan = JsonUtils.objectToPojo(req.getData(), MsChgPlanBean.class);
			MsChgPlanMapper mapper = factory.getMapper(MsChgPlanMapper.class);	
			MsChgPlanDetailMapper msChgPlanDetailMapper = factory.getMapper(MsChgPlanDetailMapper.class);
			if(StringUtils.isBlank(msChgPlan.getId())) {
				return MessageBean.create(Constant.MESSAGE_INT_FAIL, "修改失败", Void.class);
			}
			List<MsChgPlanDetailBean> msChgPlanDetails = msChgPlan.getMsChgPlanDetails();
			msChgPlan.setUpdateName(userInfo.getUserInfo().getName());
			msChgPlan.setUpdateAccount(userInfo.getUserInfo().getAcount());
			if(msChgPlan.getReceiptType() == 1) {   //换表类型
				msChgPlan.setMeterAmount(msChgPlanDetails.size());
			}
			mapper.updateMsChgPlan(msChgPlan);
			if(msChgPlan.getReceiptType() == 1) {  //换表类型
				int icount = msChgPlanDetailMapper.deleteByReceiptId(msChgPlan.getId());
				log.info("已删除{}条 ", icount);
				for(MsChgPlanDetailBean msChgPlanDetail : msChgPlanDetails) {
					if(msChgPlanDetail.getMargin() == null)
						msChgPlanDetail.setMargin(0);
					msChgPlanDetail.setCreateName(userInfo.getUserInfo().getName());
					msChgPlanDetail.setId(new ObjectId().toHexString());
					msChgPlanDetail.setReceiptId(msChgPlan.getId());
					msChgPlanDetailMapper.addMsChgPlanDetail(msChgPlanDetail);
				}
			}
			Map<String, String> data = new HashMap<String, String>();
			data.put("id", msChgPlan.getId());
			info.setData(data);
		} catch (Exception e) {
			info.setCode(Constant.MESSAGE_INT_FAIL);
			info.setDescription("修改失败");
			logger.error(e.getMessage(), e);
		}
		return info;
	}

}
